package top.infopub.mgr.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import top.infopub.concurrent.ExecutorManager;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.sys.dao.HolidaysDao;
import top.infopub.mgr.sys.service.HolidayCacheService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.model.sys.Holidays;
import top.infopub.zookeeper.confclient.listener.ConfigurationListener;

@Service("holidayService")
public class HolidayCacheServiceImpl extends GenericServiceImpl<Holidays, String> implements
		HolidayCacheService, ConfigurationListener {

    private static Logger LOGGER = LoggerFactory.getLogger(HolidayCacheServiceImpl.class);
    
    private static final String HOLIDAY ="holiday";
    
    private static List<String> caches = null;
    
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    
	@Autowired
	private HolidaysDao holidaysDao;
	
	@Override
	public GenericDao<Holidays, String> getDao() {
		return holidaysDao;
	}

	@PostConstruct
    public void loadHoliday() {
        ExecutorManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    lock.writeLock().lock();
                    caches = new ArrayList<String>();
                    caches = holidaysDao.selectRestDayBySql();
                } catch (Exception e) {
                    LOGGER.error("初始化节日缓存数据失败", e);
                } finally {
                    lock.writeLock().unlock();
                }
            }
        });
    }

    @Override
    public void configurationChangedNotice(String keyName, String value) {
        if (keyName.equalsIgnoreCase(HOLIDAY)) {
            loadHoliday();
        }
    }

    @Override
    public boolean isRestDay(Date date) {
        try {
            if (date == null) {
                return false;
            }
            lock.readLock().lock();
            if (caches == null) {
                return false;
            }
            
            if (caches != null) {
               Iterator<String> iterator = caches.iterator();
               while(iterator.hasNext()) {
                   String holiday = iterator.next();
                   if (DateUtils.dateParseShortString(date).equals(holiday)){
                       return true;
                   }
               }
            }
        } finally{
            lock.readLock().unlock();
        }
        
        return false;
    }

}